#include "app_config_store.h"

#include <ArduinoJson.h>
#include <SD.h>

AppConfigStore::AppConfigStore(const char* path) : path_(path) {}

bool AppConfigStore::GetConfig(const String& name, String& value) {
  fs::File file = SD.open(path_);
  if (!file) {
    Serial.printf("CONFIG: open %s failed!\r\n", path_);
    return false;
  }

  JsonDocument json;
  if (auto error = deserializeJson(json, file)) {
    Serial.printf("CONFIG: deserialize %s failed, %s!\r\n", path_,
                  error.c_str());
    return false;
  }

  if (!json.containsKey(name)) {
    Serial.printf("CONFIG: no key %s found!\r\n", name.c_str());
    return false;
  }

  value = json[name].as<const char*>();
  // Serial.printf("CONFIG: GetConfig(%s, %s) success!\r\n", name.c_str(),
  //               value.c_str());
  return true;
}

bool AppConfigStore::PutConfig(const String& name, const String& value) {
  JsonDocument json;
  if (SD.exists(path_)) {
    // JSON 文件已存在，读取到json对象中
    fs::File file = SD.open(path_);
    if (!file) {
      Serial.printf("CONFIG: open %s failed!\r\n", path_);
      return false;
    }

    if (auto error = deserializeJson(json, file)) {
      Serial.printf("CONFIG: deserialize json %s failed!\r\n", path_);
    }
  }

  json[name] = value;

  fs::File file = SD.open(path_, "w", true);
  if (!file) {
    Serial.printf("CONFIG: open %s for write failed!\r\n", path_);
    return false;
  }
  size_t nbytes = serializeJson(json, file);
  if (!nbytes) {
    Serial.printf("CONFIG: serialize json %s failed!\r\n", path_);
    return false;
  }
  file.flush();
  // Serial.printf("CONFIG: PutConfig(%s, %s) success!\r\n", name.c_str(),
  //               value.c_str());
  return true;
}

void AppConfigStore::PrintConfigs() {
  JsonDocument json;
  if (SD.exists(path_)) {
    // JSON 文件已存在，读取到json对象中
    fs::File file = SD.open(path_);
    if (!file) {
      Serial.printf("CONFIG: open %s failed!\r\n", path_);
      return;
    }

    if (auto error = deserializeJson(json, file)) {
      Serial.printf("CONFIG: deserialize json %s failed!\r\n", path_);
    }
  }
  serializeJsonPretty(json, Serial);
  Serial.println("");
}
